import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import store from '@/store'

const original = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return original.call(this, location).catch((err) => err)
}

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () =>
      import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  },
  {
    path: '/sign',
    name: 'sign',
    component: () => import('@/views/SignUp.vue')
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/Login.vue')
  },
  {
    path: '/help',
    name: 'help',
    component: () => import('@/views/Help.vue')
  },
  {
    path: '/doc',
    name: 'doc',
    component: () => import('@/views/Documentation.vue')
  },
  {
    path: '/user',
    name: 'user',
    component: () => import('@/views/User.vue'),
    redirect: 'table',
    children: [
      {
        path: '/table',
        name: 'table',
        component: () => import('@/components/Table.vue')
      },
      {
        path: '/account',
        name: 'account',
        component: () => import('@/components/Account.vue')
      }
    ]
  },
  // {
  //   path: '/account',
  //   name: 'account',
  //   component: () => import('@/views/Account.vue')
  // },
  {
    path: '/tools',
    name: 'tools',
    redirect: 'set',
    component: () => import('@/views/Tools.vue'),
    children: [
      {
        path: '/upload',
        name: 'upload',
        component: () => import('@/components/Upload.vue')
      },
      {
        path: '/set',
        name: 'set',
        component: () => import('@/components/Set.vue')
      },
      {
        path: '/download',
        name: 'download',
        component: () => import('@/components/Download.vue')
      }
    ],
    redirect: 'upload'
  }
]

const router = new VueRouter({
  // mode: 'history',
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, form, next) => {
  let login = localStorage.getItem('login') || null
  if (
    to.path === '/login' ||
    to.path === '/sign' ||
    to.path === '/' ||
    to.path === '/doc' ||
    to.path === '/help'
  ) {
    next()
  } else {
    const token = store.state.login
    if (!login) {
      next('/login')
    } else {
      next()
    }
  }
})

export default router
